using System.Linq;
using Headspring.Training.Core.Model;
using Headspring.Training.Core.Services;
using NHibernate;
using NHibernate.Expression;

namespace Headspring.Training.Infrastructure.Impl
{
	public class WorkOrderRepository : RepositoryBase, IWorkOrderRepository
	{
		public WorkOrderRepository(ISessionBuilder sessionFactory)
			: base(sessionFactory)
		{
		}

		public void Save(WorkOrder workOrder)
		{
			ISession session = getSession();
			ITransaction transaction = session.BeginTransaction();
			session.SaveOrUpdate(workOrder);
			transaction.Commit();
		}

		public WorkOrder GetWorkOrder(string number)
		{
			ICriteria criteria = getSession().CreateCriteria(typeof (WorkOrder));
			criteria.Add(Expression.Eq("Number", number));
			var result = criteria.UniqueResult<WorkOrder>();

			return result;
		}

		public WorkOrder[] FindWorkOrders(WorkOrderSearchSpecification specification)
		{
			ICriteria criteria = getSession().CreateCriteria(typeof (WorkOrder));

			if (specification.Assignee != null)
			{
				criteria.Add(Expression.Eq("Assignee", specification.Assignee));
			}

			if (specification.Creator != null)
			{
				criteria.Add(Expression.Eq("Creator", specification.Creator));
			}

			if (specification.Status != null)
			{
				criteria.Add(Expression.Eq("Status", specification.Status));
			}

			criteria.AddOrder(Order.Desc("LastChangeDate"));

			return criteria.List<WorkOrder>().ToArray();
		}
	}
}